import json

from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.

from ShoppingMall.models import *
from django.contrib import auth
from django.contrib.auth import logout, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required


def user_login(request):
    error_msg = ''
    # return HttpResponse("OK,Test!!!")
    if request.method == 'POST':
        user_id = request.POST.get('username')
        pwd = request.POST.get('pwd')
        user = auth.authenticate(request, username=user_id, password=pwd)
        if user is not None:
            if user.is_superuser == 0:
                login(request, user)
                return redirect('/index/')
            else:
                return redirect('/admin/')
        else:
            error_msg = '用户名或密码错误'
            # return redirect('/login/')
    return render(request, 'login.html', {'error_msg': error_msg})


def user_logout(request):
    logout(request)
    return redirect('/login/')

def user_register(request):
    error_msg = {}
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        user_pwd = request.POST.get('user_pwd')
        re_user_pwd = request.POST.get('re_user_pwd')
        user_phone = request.POST.get('user_phone')
        user_email = request.POST.get('user_email')
        if UserInfo.objects.filter(username=user_name):
            error_msg['msg'] = '用户名已存在'
        elif UserInfo.objects.filter(phone=user_phone):
            error_msg['msg'] = '该手机号已注册'
        elif user_pwd != re_user_pwd:
            error_msg['msg'] = '密码输入不一致'
        elif user_name != '' and user_pwd != '':
            UserInfo.objects.create_user(username=user_name, phone=user_phone,
                                             email=user_email, password=user_pwd)
            return HttpResponse(json.dumps({'msg':'注册成功'}, ensure_ascii=False))
        else:
            error_msg['msg'] = '用户名密码不能为空'
        if error_msg:
            return HttpResponse(json.dumps(error_msg, ensure_ascii=False))
    return render(request, 'register.html')

# 首页视图
def user_index(request):
    user1 = request.user
    print(user1)
    cakes = Cake.objects.all()  # 查询所有蛋糕
    cakeTypes = CakeType.objects.all()  # 查询蛋糕类型
    rotations = Rotation.objects.all()  # 查询轮播图
    hot_sales = HotSale.objects.all()  # 查询热销表
    shows = Show.objects.all()  # 查询展示表
    return render(request, 'index.html', {'cakes': cakes, 'cakeTypes': cakeTypes, 'rotations': rotations,
                                          'hot_sales': hot_sales, 'shows': shows})

# 单个蛋糕视图
def one_cake(request):
    cake_id = request.GET.get('id')
    cake = Cake.objects.get(id=cake_id)
    print(cake.img.img_file.url)
    template_view = 'xiangqing.html'
    return render(request, template_view, {'cake': cake})

# 查询所有蛋糕视
def all_cakes(request):
    cake_list = Cake.objects.all().order_by('id')
    cakeTypes = CakeType.objects.all()
    type_id = request.GET.get('type')  # 获取前端筛选条件，值需为类型id
    min_price = request.GET.get('min_price')  # 获取前端筛选最小价格
    max_price = request.GET.get('max_price')  # 获取前端筛选最大价格
    type1 = CakeType.objects.get(id=type_id)
    if type_id is not None and type_id is not '':
        cake_list = Cake.objects.filter(type=type_id)
    if (min_price and max_price) is not None and (min_price and max_price) is not '':
        cake_list = cake_list.filter(price__gt=min_price, price__lt=max_price)
    paginator = Paginator(cake_list, 10)  # 分页
    if request.method == "GET":
        # 获取 url 后面的 page 参数的值, 首页不显示 page 参数, 默认值是 1
        page = request.GET.get('page')
        try:
            cakes = paginator.page(page)
        # 注意捕获异常
        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            cakes = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('找不到页面的内容')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            cakes = paginator.page(paginator.num_pages)

    template_view = 'liebiao.html'
    return render(request, template_view, {'cakes': cakes, 'cakeTypes': cakeTypes,'type':type1})